package com.kuang.config;

import com.kuang.pojo.User;
import com.kuang.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;

//  自定义 UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了-->授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //info.addStringPermission("user:add");
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User对象了

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        //return null;
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了-->认证doGetAuthenticationInfo");

        //用户名，密码数据库中取
        //String username="root";
        //String password="123";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //链接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());

        //没有这个人
        if (user==null){
            return null;//抛出异常 UnknownAccountException
        }

        //往session 里面放用户
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        //可以加密  MD5加密  202CB962AC59075B964B07152D234B70  MD5盐值加密 202CB962AC59075B964B07152D234B70username
        //密码认证  shiro 做   加密了
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
